package utils

import (
	"encoding/json"
	"github.com/valyala/fasthttp"
)

// 获取余额
func GetEmailBalance() int {
	var res BalanceResp
	url := "https://api.mysubmail.com/balance/mail"
	data := &fasthttp.Args{}
	data.Add("appid", app.Submail.EmailID)
	data.Add("signature", app.Submail.EmailKey)
	status, resp, err := fasthttp.Post(nil, url, data)
	// 请求错误
	if err != nil {
		return 0
	}
	// 判断返回值
	if status != 200 {
		return 0
	}
	// 解析返回值
	err = json.Unmarshal([]byte(string(resp)), &res)
	if err != nil {
		return 0
	}
	// 返回余额
	return res.FreeBalance
}

// 发送邮件 | 一般邮件通知
func SendMail(to string, subject string, html string) bool {
	var res EmailResp
	url := "https://api.mysubmail.com/mail/send"
	data := &fasthttp.Args{}
	data.Add("appid", app.Submail.EmailID)
	data.Add("signature", app.Submail.EmailKey)
	data.Add("to", to)
	data.Add("from", "sofuny@sofuny.cn")
	data.Add("from_name", "超有趣")
	data.Add("subject", subject)
	data.Add("html", html)
	data.Add("asynchronous", "true")
	// 今日可用余额不足
	if GetEmailBalance() <= 0 {
		return false
	}
	// 发送请求
	status, resp, err := fasthttp.Post(nil, url, data)
	// 请求错误
	if err != nil {
		return false
	}
	// 判断返回值
	if status != 200 {
		return false
	}
	// 解析返回值
	err = json.Unmarshal([]byte(string(resp)), &res)
	if err != nil {
		return false
	}
	// 判断是否发送成功
	if res.Status != "success" {
		return false
	}
	return true
}
